from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from routers import user, login, course, corpus
from tools.start import init, shutdown
from fastapi.middleware.cors import CORSMiddleware
from tools.jwt_token import check_token_outTime, check_token_validity
import logging

app = FastAPI()
app.add_event_handler('startup', init)
app.add_event_handler('shutdown', shutdown)
app.include_router(user.router)
app.include_router(login.router)
app.include_router(course.router)
app.include_router(corpus.router)
# logging.basicConfig(level=logging.DEBUG)

@app.middleware("http")
async def token_auth(request: Request, call_next):
    if request.url.path in ["/login", "/docs", "/user", "/corpus", "/openapi.json"]:
        return await call_next(request)

    token = request.headers.get("Authorization")

    if not token:
        return JSONResponse(content={"msg": "Token未找到"}, status_code=401)

    access = await check_token_validity(token)

    if not access:
        return JSONResponse(content={"msg": "Token解码失败 无效的Token"}, status_code=401)

    time_out = await check_token_outTime(token)

    if not time_out:
        return JSONResponse(content={"msg": "Token已过期"}, status_code=401)

    response = await call_next(request)
    return response


# 配置 CORS
origins = [
    "http://localhost:5173",          # 允许本地开发环境
    "http://127.0.0.1/*",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,       # 允许的源列表
    allow_credentials=True,      # 是否允许发送 cookies
    allow_methods=["*"],         # 允许的 HTTP 方法（如 GET、POST 等）
    allow_headers=["*"],         # 允许的 HTTP 头部
)
@app.get("/")
async def root():
    return {"msg": "test"}

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8600,)
    # uvicorn.run(app, host="0.0.0.0", port=8600, )
